//
//  StatusPictureView.swift
//  SinaMicroblog
//
//  Created by 唐绍禹 on 15/8/7.
//  Copyright © 2015年 唐绍禹. All rights reserved.
//

import UIKit
import SDWebImage

let TSYStatusCellPictureNotification = "TSYStatusCellPictureNotification"

/// URL 的 KEY
let TSYStatusCellSelectPictureURLKey = "TSYStatusCellSelectPictureURLKey"
/// IndexPath 的 KEY
let TSYStatusCellSelectPictureIndexKey = "TSYStatusCellSelectPictureIndexKey"


class StatusPictureView: UICollectionView {
    
    var status: Status? {
        didSet {
            sizeToFit()
            //刷新视图
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calculateViewSize()
    }
    /// 计算视图大小
    private func calculateViewSize() -> CGSize {
        let itemSize = CGSize(width: 90, height: 90)
        let margin:CGFloat = 10
        
        let rowCount = 3
        pictureLayout.itemSize = itemSize
        
        let count = status?.pictureURLs?.count ?? 0
        
        if count == 0 {
            return CGSizeZero
        }
        
        if count == 1 {
            
            let key = status!.pictureURLs![0].absoluteString
            
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            var size = CGSize(width: 150, height: 120)
            
            if image != nil {
                size = image.size
            }
            
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > UIScreen.mainScreen().bounds.width ? 150 : size.width
            
            pictureLayout.itemSize = size
            return size
        }
        
        if count == 4 {
            let w = itemSize.width * 2 + margin
            return CGSize(width: w, height: w)
        }
        
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + margin * CGFloat(rowCount - 1)
        let h = itemSize.width * CGFloat(row) + margin * CGFloat(row - 1)
        return CGSize(width: w, height: h)
        
    }
    

    
    private let pictureLayout = UICollectionViewFlowLayout()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: pictureLayout)
        //清楚背景颜色
        backgroundColor = UIColor.clearColor()
        registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: "Cell")
        self.dataSource = self
        self.delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension StatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    /**
    选中单元格的代理方法
    */
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        NSNotificationCenter.defaultCenter().postNotificationName(TSYStatusCellPictureNotification , object: self, userInfo: [TSYStatusCellSelectPictureURLKey: status!.largePictureURLs!,TSYStatusCellSelectPictureIndexKey: indexPath])
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! StatusPictureCell
        
        cell.imageURL = status!.pictureURLs![indexPath.item]
        
        return cell
    }
}

class StatusPictureCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL!)
//                let key = imageURL?.absoluteString
//                iconView.image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(iconView)
        iconView.ff_Fill(contentView)
    }
    
    private lazy var iconView: UIImageView = {
        let icon = UIImageView()
        
        icon.contentMode = UIViewContentMode.ScaleAspectFill
        icon.clipsToBounds = true
        
        return icon
    
    }()
}